import type { AssetLampPostOptionsPropsType, AssetLampPostOptionsStateType } from './typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElButton,
  ElRow,
  ElCol,
  ElLoading,
  ElMessage,
  ElCard,
  ElSpace,
  // ElLink,
  ElDivider,
  ElSkeleton
} from 'element-plus'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import BasicInformation from './BasicInformation'
import MapLocation from '../components/MapLocation'
import { GUTTER, SPAN_STYLE_TWO_THIRD, SPAN_STYLE_ONE_THIRD } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../index.module.scss'

export default defineComponent({
  name: 'AssetLampPostOptions',
  props: ['record', 'type', 'cancel'],
  setup(props: AssetLampPostOptionsPropsType) {
    const store = useStore()
    const infoRef = ref() // 基础资料
    const mapLocationRef = ref() // 地图位置
    const state = reactive<AssetLampPostOptionsStateType>({
      activeTabKey: 'info',
      detail: {}
    })
    const title = { add: '新增', update: '编辑', read: '查看' }

    onMounted(() => {
      if (props?.record?.id) handleGetBasicInfoById()
    })

    // methods
    // 编辑 原内容
    const handleGetBasicInfoById = async () => {
      const loading = ElLoading.service({
        target: '.el-dialog__body'
      })
      const result = await store.dispatch('base/GetCabinetView', {
        id: props.record?.id
      })

      state.detail = result?.data
      loading.close()
    }

    // 提交表单  根据activetabkey 来判断使用哪个方法
    const handleSubmitForm = () => {
      infoRef.value.ruleFormRef.validate((valid: boolean) => {
        mapLocationRef.value.ruleFormRef.validate(async (valid2: boolean) => {
          if (!valid || !valid2) return

          const params = {
            ...infoRef.value.formValues,
            lon: mapLocationRef.value.formValues.addressCoordinates.split(',')[0] || undefined, // 经度
            lat: mapLocationRef.value.formValues.addressCoordinates.split(',')[1] || undefined, // 纬度
            address: mapLocationRef.value.formValues.address // 汉字地址
          }
          const fileList = infoRef.value.fileList.map((item: { url: any }) => item.url) || []

          params.memo = params.memo && handleTrim(params.memo) // 备注
          params.images = fileList?.length ? fileList.join(',') : '' // 图片

          const res = await store.dispatch(
            props.type === 'add' ? 'base/GetCabinetAdd' : 'base/GetCabinetUpdate',
            params
          )
          if (res?.code === 200) {
            ElMessage({ type: 'success', message: '操作成功' })
            props.cancel()
          }
        })
      })
    }

    return () => {
      const { type, cancel } = props

      return (
        <ElCard
          class={{
            'covered-with-info-content': true,
            'covered-with-info-has-option-btn': true,
            [styles['info-card-box']]: true
          }}
          v-slots={{
            header: () => (
              <ElSpace class="info-card-header-space">
                <SaasTitle type="primary">机柜{(title[type] as string) || '查看'}</SaasTitle>
                <ElButton text type="primary" onClick={props.cancel}>
                  返回上一级&nbsp;
                  <AliIcon type="icon-fanhuishangyiji" />
                </ElButton>
              </ElSpace>
            )
          }}
        >
          {type === 'add' || state.detail?.id ? (
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_ONE_THIRD}>
                <BasicInformation ref={infoRef} detail={state.detail} type={props.type} />
              </ElCol>
              <ElCol {...SPAN_STYLE_TWO_THIRD} class={styles['map-location']}>
                <MapLocation ref={mapLocationRef} detail={state.detail} />
              </ElCol>
            </ElRow>
          ) : (
            <ElSkeleton rows={5} animated />
          )}
          {type !== 'read' && (
            <section class="fixed-option-btns">
              <ElDivider />
              <ElSpace class="form-options-btns">
                <ElButton plain onClick={cancel}>
                  取消
                </ElButton>
                <ElButton type="primary" onClick={handleSubmitForm}>
                  保存
                </ElButton>
              </ElSpace>
            </section>
          )}
        </ElCard>
      )
    }
  }
})
